package com.ktmall.controller;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.ktmall.pojo.WeChatPhoneInfo;
import com.ktmall.pojo.WxUser;
import com.ktmall.service.WxUserService;
import com.ktmall.utils.RespMsg;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Properties;
import java.util.UUID;

@Api(tags = "手机号登录相关接口")
@RestController
@RequestMapping("/uni")
public class PhoneLoginController {
    private final static String appId ;
    private final static String secret ;
    private final static String accessTokenhttps ;
    private final static String webAccessTokenhttps ;

    @Autowired
    private WxUserService wxUserService;

   static String configFile = "application.properties";//微信配制文件路径

    static {
        Properties properties = new Properties();
        try {
            properties.load(PhoneLoginController.class.getClassLoader().getResourceAsStream(configFile));
            appId=properties.getProperty("wx.appId");
            accessTokenhttps=properties.getProperty("wx.accessTokenhttps");
            secret = properties.getProperty("wx.secret");
            webAccessTokenhttps = properties.getProperty("wx.webAccessTokenhttps");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    @ApiOperation("获取用户手机号")
    @RequestMapping("/phoneLogin")
    public RespMsg phoneLogin(String code,String loginCode){
        RespMsg msg = null;
        if(code == null || code == ""){
            msg = RespMsg.fail("手机号码获取凭证不能为空！");
            return msg;
        }
        if(loginCode == null || loginCode == ""){
            msg = RespMsg.fail("临时登录凭证不能为空！");
            return msg;
        }
        //思路：获取手机号码前先试用openId查询t_wx_user微信用户表中的数据，如果之前注册过就直接将微信用户信息响应到小程序
        //反之再获取手机号码然后进行注册，即向t_wx_user微信用户
        //1.获取开发者id
        String openId = getOpenId(loginCode);
        if(openId == null || openId == ""){
            msg = RespMsg.fail("openId获取失败");
            return msg;
        }
        //2.根据openId开发者id查询t_wx_user微信用户
        WxUser wxUser = wxUserService.findByOpenId(openId);
        if(wxUser == null){//注册
            /**
             * 1.获取接口调用凭证
             */
            String url1 = String.format(accessTokenhttps,appId,secret);
            String resp = HttpUtil.get(url1);

            //JSONObject导的包时：com.alibaba.fastjson.JSONObject
            JSONObject jsonObject = JSONObject.parseObject(resp);
            String accessToken = jsonObject.getString("access_token");
            //如果请求失败则会返回errcode和errmsg这个两个数据，所以只需要判断这个两个数据是否为空，就可以判断手机号码是否授权成功
            if(jsonObject.getString("errcode") != null){
                msg = RespMsg.fail("手机号授权失败",jsonObject.getString("errmsg"));
                return msg;
            }

            //2.通过accessToken和code来获取用户手机号-
            String phoneNumber = getPhoneNumber(code,accessToken);
            if(phoneNumber == null){
                msg = RespMsg.fail("手机号获取失败",jsonObject.getString("errmsg"));
                return msg;
            }
            wxUser = new WxUser();
            wxUser.setUsername("科泰购用户" + UUID.randomUUID());
            wxUser.setOpenId(openId);
            wxUser.setLastLoginIp("0:0:0:0:0:0:1");
            wxUser.setMobile(phoneNumber);
            wxUser.setPassword("123456");
            wxUser.setLastLoginTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            wxUser.setAvatar("https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0");
            wxUser.setNickname("科泰购昵称" + UUID.randomUUID());

            wxUserService.insert(wxUser);   //注册
        }else{
            wxUser.setLastLoginTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            wxUserService.updateLastLoginTime(wxUser.getId());
        }
        wxUser.setToken("wx" + UUID.randomUUID());
        msg = RespMsg.success("登录成功",wxUser);
        return msg;
    }

    private String getPhoneNumber(String code, String accessToken) {
        String baseUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+accessToken;
        HashMap<String,Object> requestParams = new HashMap<String,Object>();
        requestParams.put("code",code);
        String params = JSONUtil.toJsonStr(requestParams);
        HttpResponse httpResponse = HttpRequest.post(baseUrl).
                header(Header.CONTENT_ENCODING,"UTF-8"). //设置请求编码
                timeout(60*1000).//设置超时时间
                header(Header.CONTENT_TYPE,"application/x-www-form-urlencoded"). //设置请求内容信息
                body(params) //填充参数
                .execute();//发送请求
        String body = httpResponse.body();//获取响应体对象
        cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(body); //将body转化为json对象
        WeChatPhoneInfo weChatPhoneInfo = jsonObject.get("phone_info",WeChatPhoneInfo.class);
        //返回手机号码
        return weChatPhoneInfo.getPhoneNumber();
    }

    private String getOpenId(String loginCode) {
        String url2 = String.format(webAccessTokenhttps,appId,secret,loginCode);
        String resp = HttpUtil.get(url2);
        JSONObject jsonObject = JSONObject.parseObject(resp);
        return jsonObject.getString("openid");
    }
}
